/**
 * All rights Reserved, Designed By Android_Robot
 *
 * @Title: CanTouchImageView.java
 * @Package com.jiyi.widget
 * @Description: TODO(用一句话描述该文件做什么)
 * @author: HYM
 * @date: 2017-5-16 下午2:59:08
 * @version V1.0
 */
package com.jiyi.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.jiyi.bean.owner.PositionPoint;
import com.jiyi.inteface.PhotoClickInterface;
import com.jiyi.widget.picshow.PhotoViewAttacher;
import com.jiyi.widget.picshow.PhotoViewAttacher.OnPhotoTapListener;
import com.jiyi.widget.picshow.PhotoViewAttacher.OnViewTapListener;
import com.swift.maintenance.utils.ToastUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import static org.xutils.common.util.IOUtil.copy;

/**
 * @ClassName: CanTouchImageView
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-5-16 下午2:59:08
 */
public class CanTouchImageView extends android.support.v7.widget.AppCompatImageView {

    // where the user tapped from the of the Drawable, as percentage of the
    // Drawable width and height.
    public float mX = 0, mY = 0;
    // 原图像，添加放置的图像
    Bitmap bmp, waterBitmap, bmpNoCur, bmpNoCur2;
    // 图片插件
    PhotoViewAttacher mAttacher;
    // 点击回调
    PhotoClickInterface mPhotoClickInterface;
    // 本身对象
    ImageView imageView = this;

    // 是否可以点击新增
    // boolean isCanClick = false;
    // 点击的状态 0 不可操作 1 可添加 2 查看 3 修改
    int click_status = 1;

    private ArrayList<PositionPoint> positionPoints;// 装标注点信息的点
    Context mContext;

    int index;
    boolean isRef = true;
    boolean isOnDraw = false;
    boolean isChange = false;
    boolean isShow = false;
    private Timer mTimer;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                //这里可以进行UI操作，如Toast，Dialog等
                index++;
                if (positionPoints != null) {
                    if (positionPoints.size() > 0) {
                        if (index >= positionPoints.size() - 1) {
                            index = 0;
                        }
                        ref();
                    }
                }


            }
        }
    };


    public CanTouchImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 初始化关联插件

        startime = System.currentTimeMillis();
        mContext = context;
        attchView(this);
        start();
    }

    private void start() {
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 0;
                mHandler.sendMessage(message);
            }
        }, 0, 1200);
    }


    public void stop() {
        mTimer.cancel();
    }


    /**
     * @param src         源图片
     * @param watermark   需要添加的图片
     * @param x           x轴
     * @param y           y轴
     * @param isHighLignt 是否高亮
     * @return Bitmap 新的图片
     * @author: HYM
     * @Title: createBitmap
     * @Description: TODO(创建一个新的bitmap)
     * @date: 2017-5-17
     */
    private Bitmap createBitmap(Bitmap src, Bitmap watermark, final float x, final float y,
                                boolean isHighLignt, int color, int alpha) {
        Log.e("createBitmap start:", System.currentTimeMillis() + "");

        // 源图片不能空
        if (src == null) {
            return null;
        }
        Paint p = new Paint();
        p.setAlpha(alpha);
        // 获取源图片宽
        final int w = src.getWidth();
        // 获取源图片高
        final int h = src.getHeight();
        // 获取水印图片宽
        final int ww = watermark.getWidth();
        // 获取水印图片高
        final int wh = watermark.getHeight();
        // 创建一个新的和源图片长度宽度一样的位图
        Bitmap newb = Bitmap.createBitmap(w, h, Config.RGB_565);
        final Canvas cv = new Canvas(newb);
        // 在 0，0坐标开始画入src
        cv.drawBitmap(src, 0, 0, null);

        watermark = drawBg4Bitmap(color, watermark);

//        if (isHighLignt) {
//            // 高亮
//            watermark = drawBg4Bitmap(color, watermark);
//        } else {
//            // 蒙板
//            watermark = drawBg4Bitmap(R.color.half_half_half_transparency,
//                    watermark);
//        }

        // 在源图片的x,y轴画入水印
        cv.drawBitmap(watermark, w * x - ww / 2, h * y - wh / 2, p);

        // 保存
        cv.save(Canvas.ALL_SAVE_FLAG);
        // 存储
        cv.restore();

        Log.e("createBitmap end:", System.currentTimeMillis() + "");
        return newb;
    }


    /**
     * @author: HYM
     * @Title: bind
     * @Description: TODO(插件与图片的管理，并监听点击事件) void
     * @date: 2017-5-17
     */
    void bind() {
        new MyAsyncTask(bmpNoCur == null ? bmpNoCur = bmp : bmpNoCur,
                waterBitmap, this).execute("");
    }

    public Bitmap getWaterBitmap() {
        return waterBitmap;
    }

    public void setWaterBitmap(Bitmap waterBitmap) {
        this.waterBitmap = waterBitmap;
    }

    public Bitmap getBmp() {
        return bmp;
    }

    public void setBmp(Bitmap bmp) {
        this.bmp = bmp;
    }

    /**
     * @param view void
     * @author: HYM
     * @Title: attchView
     * @Description: TODO(关联插件)
     * @date: 2017-5-17
     */
    void attchView(ImageView view) {
        // 图像插件重新管理当前图像
        mAttacher = new PhotoViewAttacher(view);
        mAttacher.setOnPhotoTapListener(new OnPhotoTapListener() {

            @Override
            public void onPhotoTap(View view, float x, float y, float xRatio, float yRatio) {
                // 只保留x,y轴两位小数
                DecimalFormat decimalFormat = new DecimalFormat(".0000");
                String xTemp = decimalFormat.format(xRatio);
                String yTemp = decimalFormat.format(yRatio);
                mX = Float.parseFloat(xTemp);
                mY = Float.parseFloat(yTemp);
                Log.d("onPhotoTap::   ", "x:   " + x);
                Log.d("onPhotoTap::   ", "y:   " + y);
                Log.d("onPhotoTap::   ", "xRatio:   " + xRatio);
                Log.d("onPhotoTap::   ", "yRatio:   " + yRatio);

                // 判断是否可以开始操作
                if (click_status == 2) {
                    // ToastUtil.getInstances().showMsg("请先点击选取坐标按钮");
                    // 判断是否有点击到存在的点
                    if (positionPoints != null) {
                        for (int i = 0; i < positionPoints.size(); i++) {
                            PositionPoint point = positionPoints.get(i);
                            if (point.getPointX() + 0.01 >= mX
                                    && point.getPointX() - 0.01 < mX
                                    && point.getPointY() + 0.01 >= mY
                                    && point.getPointY() - 0.01 < mY) {
                                Log.e("dsdf   ", "点击了" + point.getId());
                                if (!isShow) {
                                    isOnDraw = false;
                                    mPhotoClickInterface.onPointClick(point.getId(), x, y, xRatio, yRatio);
                                }

                                return;
                            }
                        }
                    }
                    return;
                } else if (click_status == 1) {
                    // 判断是否源图片
                    if (bmp == null) {
                        return;
                    }
                    // 判断是否有放置物品
                    if (waterBitmap == null) {
                        ToastUtil.getInstances().showMsg("请先选择设备类型");
                        return;
                    }

                    bind();
                    // mPhotoClickInterface.onPhotoClcik(Float.parseFloat(view.getTag(R.id.tag_pic_x).toString()),Float.parseFloat(view.getTag(R.id.tag_pic_y).toString()));
                    mPhotoClickInterface.onPhotoClcik(x, y, mX, mY);
                } else if (click_status == 0) {
                    ToastUtil.getInstances().showMsg("请先点击选取坐标按钮");
                    return;
                } else if (click_status == 3) {
                    // 判断是否源图片
                    if (bmp == null) {
                        return;
                    }
                    // 判断是否有放置物品
                    if (waterBitmap == null) {
                        ToastUtil.getInstances().showMsg("请先选择设备类型");
                        return;
                    }
                    mPhotoClickInterface.onPhotoClcik(x, y, mX, mY);
                    return;
                }
            }
        });
        mAttacher.setOnViewTapListener(new OnViewTapListener() {

            @Override
            public void onViewTap(View view, float x, float y) {
                Log.d("onViewTap::   ", "x:   " + x);
                Log.d("onViewTap::   ", "y:   " + y);
                ToastUtil.getInstances().showMsg("请点击图片区域");
            }
        });

        //是否允许父控件的事件 true 是  false 否
        mAttacher.setAllowParentInterceptOnEdge(true);
    }


    /**
     * 设置透明度
     */
    public int degree = 255;

    public int getDegree() {
        return degree;
    }

    public void setDegree(int degree) {
        this.degree = degree;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }


    public void ref() {
        isShow=true;

        if (isOnDraw) {
            if (isRef) {
                for (int j = 0; j < positionPoints.size(); j++) {

                    final int finalJ = j;
                    Glide.with(this.getContext()).load(positionPoints.get(j).getIcon())
                            .asBitmap().into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap bitmap,
                                                    GlideAnimation glideAnimation) {
                            int alpha;
                            if (positionPoints.get(finalJ).isWx()) {
                                alpha = 30;
                            } else {
                                alpha = 255;
                            }
                            int color = positionPoints.get(finalJ).getColor();
                            loadWaterList(bitmap, positionPoints.get(finalJ).getPointX(), positionPoints.get(finalJ).getPointY(), positionPoints.get(finalJ).isSelect(), color, alpha);
                        }
                    });

                    if (j == positionPoints.size() - 1) {
                        isRef = false;
                        ref();
                    }
                }
            } else {
                loadWaterList2();
            }
        }
    }

    /**
     * @ClassName: MyAsyncTask
     * @Description:TODO(点击放置设备的执行方法)
     * @author: HYM
     * @date: 2017-5-18 下午2:46:17
     */
    public class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {
        Bitmap cur, water;
        CanTouchImageView my;

        public MyAsyncTask(Bitmap cur, Bitmap water, CanTouchImageView my) {
            this.cur = cur;
            this.water = water;
            this.my = my;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            // 用户放置后替换当前图像为放置后的图像
            Bitmap temp = createBitmap(cur, water, mX, mY, true, Color.RED, 255);
            return temp;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            Log.e("onPostExecute start:", System.currentTimeMillis() + "");
            super.onPostExecute(result);
            // 用户放置后替换当前图像为放置后的图像
            my.setImageBitmap(result);
            Log.e("onPostExecute end:", System.currentTimeMillis() + "");
        }
    }


    /**
     * @ClassName: LoadDefAsyncTask
     * @Description:TODO(界面初始化异步添加水印) 生成没闪烁的点
     * @author: HYM
     * @date: 2017-5-17 下午5:37:27
     */
    public class LoadDefAsyncTask extends AsyncTask<String, Integer, Bitmap> {
        Bitmap water;
        float x, y;
        boolean isHighLignt, isTwinkle;
        int alpha, color;

        public LoadDefAsyncTask(Bitmap water, float x, float y,
                                boolean isHighLignt, boolean isTwinkle, int color, int alpha) {
            this.water = water;
            this.x = x;
            this.y = y;
            this.isHighLignt = isHighLignt;
            this.isTwinkle = isTwinkle;
            this.alpha = alpha;
            this.color
                    = color;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            // 判断当前是否是只有一个设备
            if (bmpNoCur == null) {
                bmpNoCur = bmp;
            }

//            if (issh == false) {
//                bmpNoCur = bmpNoCur2;
//            }

//            if (isTwinkle && bmpNoCur2 != null) {
//                bmpNoCur = bmpNoCur2;
//            }


            bmpNoCur = createBitmap(bmpNoCur, water, x, y, isHighLignt, color, alpha);
            bmpNoCur2 = bmpNoCur;
//            if (!isTwinkle) {
//                bmpNoCur2 = bmpNoCur;
//            }

//            if (issh) {
//                bmpNoCur2 = bmpNoCur;
//                issh=false;
//            }
//             if (!isHighLignt) {
//             bmpNoCur = bmp;
//             }
            return bmpNoCur;

        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            // 用户放置后替换当前图像为放置后的图像
            setImageBitmap(result);

        }
    }


    /**
     * 异步添加闪烁的水印
     */
    public class LoadDefAsyncTask2 extends AsyncTask<String, Integer, Bitmap> {

        public LoadDefAsyncTask2() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... params) {

            isChange = !isChange;
            if (isChange) {
                return bmpNoCur2;
            } else {
                bmpNoCur = bmpNoCur2;
                return generate();
            }
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            // 用户放置后替换当前图像为放置后的图像
            setImageBitmap(result);
            isShow=false;
        }
    }

    /**
     * 重置成最原始的bmp
     */
    public class LoadDefAsyncTask3 extends AsyncTask<String, Integer, Bitmap> {

        public LoadDefAsyncTask3() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... params) {

           return bmpNoCur;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            // 用户放置后替换当前图像为放置后的图像
            setImageBitmap(result);
        }
    }


    /**
     * 生成平面图上的点bitmap
     *
     * @param url 图片地址
     */
    public Bitmap GetLocalOrNetBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new URL(url).openStream());
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            data = null;
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 循环生成闪烁的点
     * @return
     */
    private Bitmap generate() {
        for (int i = 0; i < positionPoints.size(); i++) {
            if (positionPoints.get(i).isWx()) {
                final int finalJ = i;
                int color;
                if (positionPoints.get(finalJ).getAlarm_status() == 1) {
                    color = Color.parseColor("#e49319");//橙色
                } else {
                    color = Color.parseColor("#ff0004");//红色
                }

                PositionPoint p = positionPoints.get(finalJ);


//
//                Glide.with(mContext).load(positionPoints.get(finalJ).getIcon())
//                        .asBitmap().into(new SimpleTarget<Bitmap>() {
//                    @Override
//                    public void onResourceReady(Bitmap bitmap,
//                                                GlideAnimation glideAnimation) {
////
//                        Logger.d("bitmap:1:" + bitmap);
//
//
//                    }
//                });
//
//                Logger.d("bitmap:2:" + GetLocalOrNetBitmap(positionPoints.get(finalJ).getIcon()));

                Bitmap b = GetLocalOrNetBitmap(positionPoints.get(finalJ).getIcon());
                if (b != null) {
                    bmpNoCur = createBitmap(bmpNoCur, b, p.getPointX(), p.getPointY(), false, color, 255);
                }


            }
        }

        return bmpNoCur;
    }


    /**
     * @param water
     * @param x
     * @param y     void
     * @author: HYM
     * @Title: loadWaterList
     * @Description: TODO(添加水印的方法)
     * @date: 2017-5-17
     */
    public void loadWaterList(Bitmap water, float x, float y,
                              boolean isHighLignt, int color, int aplha) {
        synchronized (this) {
            new LoadDefAsyncTask(water, x, y, isHighLignt, false, color, aplha).execute("");
        }
    }


    /**
     * 添加闪烁的水印
     */
    public void loadWaterList2() {
        synchronized (this) {
            new LoadDefAsyncTask2().execute("");
        }
    }


    public PhotoClickInterface getmPhotoClickInterface() {
        return mPhotoClickInterface;
    }

    public void setmPhotoClickInterface(PhotoClickInterface mPhotoClickInterface) {
        this.mPhotoClickInterface = mPhotoClickInterface;
    }

    static long startime = 0;

    /**
     * @param color
     * @param orginBitmap
     * @return Bitmap
     * @author: HYM
     * @Title: drawBg4Bitmap
     * @Description: TODO(Bitmap换背景颜色)
     * @date: 2017-5-18
     */
    public Bitmap drawBg4Bitmap(int color, Bitmap orginBitmap) {
        Paint paint = new Paint();
        paint.setColor(color);
        paint.setAlpha(degree);
        Bitmap bitmap = Bitmap.createBitmap(orginBitmap.getWidth(),
                orginBitmap.getHeight(), orginBitmap.getConfig());
        Canvas canvas = new Canvas(bitmap);
        // 画圆形背景
        canvas.drawCircle(orginBitmap.getWidth() / 2,
                orginBitmap.getHeight() / 2, orginBitmap.getWidth() / 2, paint);
        // 画矩形背景
        // canvas.drawRect(0, 0, orginBitmap.getWidth(),
        // orginBitmap.getHeight(), paint);
        canvas.drawBitmap(orginBitmap, 0, 0, paint);
        return bitmap;
    }


    // public boolean isCanClick() {
    // return isCanClick;
    // }
    //
    // public void setCanClick(boolean isCanClick) {
    // this.isCanClick = isCanClick;
    // }

    public ArrayList<PositionPoint> getPositionPoints() {
        return positionPoints;
    }

    public void setPositionPoints(ArrayList<PositionPoint> positionPoints, boolean isOnDraw) {
        this.positionPoints = positionPoints;
        if (isOnDraw) {
            this.isRef = false;
        } else {
            this.isRef = true;
        }
        this.isOnDraw = true;

    }

    public int getClick_status() {
        return click_status;
    }

    public void setClick_status(int click_status) {
        this.click_status = click_status;
    }

    public void reset() {

        bmpNoCur = bmp;
        synchronized (this) {
            new LoadDefAsyncTask3().execute("");
        }
    }
}
